package gw.com.android.presenter;

import com.gwtsz.gts2.hx.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.DoubleConverter;
import www.com.library.util.JsonUtil;
import www.com.library.util.StringFormatter;

/**
 * Created by reeta.zou on 2017/3/10.
 * 合约属性界面及层级保证金逻辑处理
 */

public class PropertyPresenter extends BasePresenter {

    private int mUiCode;
    private int mZone;
    public DataItemDetail model;
    public JSONArray mTradeTime;
    public DataItemResult mMarginList;
    private DataItemDetail mMarginModel;
    public double rate = 0;
    public boolean isEmpty = false;//标识合约属性是否显示空
    public boolean isMargin = false;//标识是否开启层级保证金
    public boolean isMore = false;//标识是否有多层，保证金可以点击下拉
    public boolean isCNY = false;//标识是否是人民币账号

    public PropertyPresenter(int code, int mZone) {
        mUiCode = code;
        this.mZone = mZone;
        model = new DataItemDetail();
        mMarginList = new DataItemResult();
        isMargin = DataManager.instance().hasMargin();
        isCNY = DataManager.instance().isCNY();
        setPropertyData();
    }

    private void setPropertyData(){
        DataItemDetail item = DataManager.instance().getTickModel(GTSConst.CNY_CODE);
        if(null != item){
            rate = DoubleConverter.toDoubleData(item.getString(GTSConst.JSON_KEY_CURPRICE));
        }else{
            rate = 0;
        }
        DataItemDetail tickModel = DataManager.instance().getTickModel(mUiCode);
        if (GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_GUEST
                && null != tickModel && mZone != GTSConst.ZONE_TYPE_REF
                && tickModel.getInt(GTSConst.JSON_KEY_TRADESTATE) != AppContances.TRADE_STATU_REF) {
            isEmpty = false;
            String jsonStr = AppTerminal.instance().getProtertyModel(mUiCode);
            Logger.e("jsonStr == " + jsonStr);
            try {
                if (JsonUtil.isJsonData(jsonStr)) {
                    JSONObject mArray = new JSONObject(jsonStr);
                    model.clear();
                    JsonUtil.toDataItemDetail(model, mArray);
                    mTradeTime = mArray.getJSONArray(GTSConst.JSON_KEY_TRADETIME);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            isEmpty = true;
            mTradeTime = new JSONArray();
        }
    }

    public DataItemResult getPropertyData() {
        DataItemResult mListData = new DataItemResult();
        DataItemDetail item;

        item = new DataItemDetail();
        item.setStringValue("title", AppMain.getAppString(R.string.property_contract_unit));
        item.setStringValue("value", getStr(model.getString(GTSConst.JSON_KEY_CONTRACTSIZE)));
        mListData.addItem(item);

        //外汇显示基准和收益货币，其他显示货币单位，
        if (mZone == GTSConst.ZONE_TYPE_FX) {
            item = new DataItemDetail();
            item.setStringValue("title", AppMain.getAppString(R.string.property_base_currency));
            item.setStringValue("value", getStr(model.getString(GTSConst.JSON_KEY_BASECURRENCY)));
            mListData.addItem(item);

            item = new DataItemDetail();
            item.setStringValue("title", AppMain.getAppString(R.string.property_profit_currency));
            item.setStringValue("value", getStr(model.getString(GTSConst.JSON_KEY_PROFITCURRENCY)));
            mListData.addItem(item);
        } else {
            item = new DataItemDetail();
            item.setStringValue("title", AppMain.getAppString(R.string.property_currency_unit));
            item.setStringValue("value", getStr(model.getString(GTSConst.JSON_KEY_TYPE)));
            mListData.addItem(item);
        }

        item = new DataItemDetail();
        item.setStringValue("title", AppMain.getAppString(R.string.property_double_sum));
        item.setStringValue("value", getStr(model.getString(GTSConst.JSON_KEY_DIGITS)));
        mListData.addItem(item);

        item = new DataItemDetail();
        item.setStringValue("title", AppMain.getAppString(R.string.property_spreads_rebate));
        String diff = getStr(model.getString(GTSConst.JSON_KEY_DIFF));

        if (diff.length() > 0) {
            if(ConfigUtil.instance().hasSpreadFixFunction()){
                diff = AppMain.getAppString(R.string.property_spreads_rebate_value2);
            }else{
                if (DoubleConverter.toFloatData(diff) != 0) {
                    diff = AppMain.getAppString(R.string.property_spreads_rebate_value2);
                } else {
                    diff = AppMain.getAppString(R.string.property_spreads_rebate_value);
                }
            }
        }
        item.setStringValue("value", diff);
        mListData.addItem(item);

        item = new DataItemDetail();
        item.setStringValue("title", AppMain.getAppString(R.string.property_lots_single_transaction));
        item.setStringValue("value", getStr(model.getString(GTSConst.JSON_KEY_VOLUMESMIN), R.string.property_lot).length() < 1 ? "":
                getStr(model.getString(GTSConst.JSON_KEY_VOLUMESMIN), R.string.property_lot) +"~"+ getStr(model.getString(GTSConst.JSON_KEY_VOLUMESMAX), R.string.property_lot));
        mListData.addItem(item);

        item = new DataItemDetail();
        item.setStringValue("title", AppMain.getAppString(R.string.property_small_append_distance));
        item.setStringValue("value", getStr(model.getString(GTSConst.JSON_KEY_MINPIP)));
        mListData.addItem(item);

        item = new DataItemDetail();
        item.setStringValue("title", AppMain.getAppString(R.string.property_lot_difference));
        item.setStringValue("value", getStr(model.getString(GTSConst.JSON_KEY_VOLUMESSTEP), R.string.property_lot));
        mListData.addItem(item);

//        item = new DataItemDetail();
//        item.setStringValue("title", AppMain.getAppString(R.string.property_position_ceiling));
//        item.setStringValue("value", getStr(model.getString(GTSConst.JSON_KEY_POSMAX), R.string.property_lot));
//        mListData.addItem(item);

        if (isMargin) {
            setMarginLevel();
            item = new DataItemDetail();
            item.setStringValue("title", AppMain.getAppString(R.string.property_margin_over_city));
            if (isCNY) {
                item.setStringValue("value", getStr(mMarginModel.getString(GTSConst.JSON_KEY_MARGININITIAL),
                        isMore ? R.string.property_low_margin_over_city_value_cny : R.string.property_margin_over_city_value_cny));
            } else {
                item.setStringValue("value", getStr(mMarginModel.getString(GTSConst.JSON_KEY_MARGININITIAL),
                        isMore ? R.string.property_low_margin_over_city_value : R.string.property_margin_over_city_value));
            }
            item.setStringValue(GTSConst.JSON_KEY_PROPERTY_LOTS, mMarginModel.getString(GTSConst.JSON_KEY_PROPERTY_LOTS));
            item.setStringValue(GTSConst.JSON_KEY_PROPERTY_MARGIN, mMarginModel.getString(GTSConst.JSON_KEY_PROPERTY_MARGIN));
            mListData.addItem(item);

            item = new DataItemDetail();
            item.setStringValue("title", AppMain.getAppString(R.string.property_margin_over_holiday));
            if (isCNY) {
                item.setStringValue("value", getStr(mMarginModel.getString(GTSConst.JSON_KEY_HOLIDAYMARGININITIAL),
                        isMore ? R.string.property_low_margin_over_city_value_cny : R.string.property_margin_over_city_value_cny));
            } else {
                item.setStringValue("value", getStr(mMarginModel.getString(GTSConst.JSON_KEY_HOLIDAYMARGININITIAL),
                        isMore ? R.string.property_low_margin_over_city_value : R.string.property_margin_over_city_value));
            }
            item.setStringValue(GTSConst.JSON_KEY_PROPERTY_LOTS, mMarginModel.getString(GTSConst.JSON_KEY_PROPERTY_LOTS));
            item.setStringValue(GTSConst.JSON_KEY_PROPERTY_HOLIDAYMARGIN, mMarginModel.getString(GTSConst.JSON_KEY_PROPERTY_HOLIDAYMARGIN));
            mListData.addItem(item);

            item = new DataItemDetail();
            item.setStringValue("title", AppMain.getAppString(R.string.property_hedged_margin));
            if (null != mMarginModel.getString(GTSConst.JSON_KEY_MARGINHEDGED) && mMarginModel.getString(GTSConst.JSON_KEY_MARGINHEDGED).length() > 0) {
                mMarginModel.setStringValue(GTSConst.JSON_KEY_MARGINHEDGED, mMarginModel.getString(GTSConst.JSON_KEY_MARGINHEDGED) + "%");
            }
            item.setStringValue("value", getStr(mMarginModel.getString(GTSConst.JSON_KEY_MARGINHEDGED), R.string.property_hedged_margin_value));
            mListData.addItem(item);
        } else {
            item = new DataItemDetail();
            item.setStringValue("title", AppMain.getAppString(R.string.property_margin_over_city));
            if (isCNY) {
                item.setStringValue("value", getStr(model.getString(GTSConst.JSON_KEY_MARGININITIAL), R.string.property_margin_over_city_value_cny));
            } else {
                item.setStringValue("value", getStr(model.getString(GTSConst.JSON_KEY_MARGININITIAL), R.string.property_margin_over_city_value));
            }
            mListData.addItem(item);

            item = new DataItemDetail();
            item.setStringValue("title", AppMain.getAppString(R.string.property_margin_over_holiday));
            if (isCNY) {
                item.setStringValue("value",getStr(model.getString(GTSConst.JSON_KEY_HOLIDAYMARGININITIAL), R.string.property_margin_over_city_value_cny));
            } else {
                item.setStringValue("value", getStr(model.getString(GTSConst.JSON_KEY_HOLIDAYMARGININITIAL), R.string.property_margin_over_city_value));
            }
            mListData.addItem(item);

            item = new DataItemDetail();
            item.setStringValue("title", AppMain.getAppString(R.string.property_hedged_margin));
            if (null != model.getString(GTSConst.JSON_KEY_MARGINHEDGED) && model.getString(GTSConst.JSON_KEY_MARGINHEDGED).length() > 0) {
                model.setStringValue(GTSConst.JSON_KEY_MARGINHEDGED, model.getString(GTSConst.JSON_KEY_MARGINHEDGED) + "%");
            }
            item.setStringValue("value", getStr(model.getString(GTSConst.JSON_KEY_MARGINHEDGED), R.string.property_hedged_margin_value));
            mListData.addItem(item);
        }

        item = new DataItemDetail();
        item.setStringValue("title", AppMain.getAppString(R.string.property_overnight_interest));
        String str = getStr(model.getString(GTSConst.JSON_KEY_LONGSWAP));
        if (str.length() > 0) {
            str = str + "%/" + getStr(model.getString(GTSConst.JSON_KEY_SHORTSWAP)) + "%";
        }
        item.setStringValue("value", str);
        mListData.addItem(item);

        item = new DataItemDetail();
        item.setStringValue("title", AppMain.getAppString(R.string.property_interest_day_three_days));
        item.setStringValue("value", getStr(model.getString(GTSConst.JSON_KEY_THREEDAYSSWAP)).length() > 0 ? getWeek(getStr(model.getString(GTSConst.JSON_KEY_THREEDAYSSWAP))) : "");
        mListData.addItem(item);

        item = new DataItemDetail();
        item.setStringValue("title", AppMain.getAppString(R.string.property_trading_hours, StringFormatter.instance().getZoneTime()));
        item.setStringValue("value", getTradeTime(mTradeTime));
        mListData.addItem(item);

        item = new DataItemDetail();
        item.setStringValue("title", AppMain.getAppString(R.string.property_settlement_time));
        item.setStringValue("value", getStr(model.getString(GTSConst.JSON_KEY_SETTLENTIME), R.string.property_settlement_time_value));
        mListData.addItem(item);

        //原油和指数，显示合约到期时间
        if (mZone == GTSConst.ZONE_TYPE_OIL || mZone == GTSConst.ZONE_TYPE_INDEX) {
            item = new DataItemDetail();
            item.setStringValue("title", AppMain.getAppString(R.string.property_expiry_time));
            if(model.getInt(GTSConst.JSON_KEY_EXPIRETIME) > 0){
                item.setStringValue("value", getStr(StringFormatter.instance().secToDateTime(model.getInt(GTSConst.JSON_KEY_EXPIRETIME))));
            }else{
                item.setStringValue("value", "");
            }
            mListData.addItem(item);
        }

        item = new DataItemDetail();
        item.setStringValue("title", AppMain.getAppString(R.string.property_note_msg));
        mListData.addItem(item);

        return mListData;
    }

    /**
     * 处理层级保证金逻辑
     */
    private void  setMarginLevel(){
        if (!isEmpty) {
            String jsonStr2 = AppTerminal.instance().getMarginLevel(mUiCode);
            Logger.e("jsonStr2 == " + jsonStr2);
            try {
                if (JsonUtil.isJsonData(jsonStr2)) {
                    JSONArray mArray2 = new JSONArray(jsonStr2);
                    mMarginList.clear();
                    JsonUtil.toDataItemResult(mMarginList, mArray2);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        mMarginModel = new DataItemDetail();
        if(mMarginList.getDataCount() > 0){
            if(mMarginList.getDataCount() > 1){
                isMore = true;
            }else{
                isMore = false;
            }
            String lots = AppMain.getAppString(R.string.property_lots_range);
            String margin = AppMain.getAppString(R.string.property_margin_range);
            String holidayMargin = AppMain.getAppString(R.string.property_margin_range);
            for (int i = 0; i < mMarginList.getDataCount(); i++) {
                DataItemDetail item = mMarginList.getItem(i);
                if(i == 0){
                    mMarginModel.setStringValue(GTSConst.JSON_KEY_MARGININITIAL, calCNY(isCNY,item.getString(GTSConst.JSON_KEY_MARGININITIAL)));
                    mMarginModel.setStringValue(GTSConst.JSON_KEY_HOLIDAYMARGININITIAL, calCNY(isCNY,item.getString(GTSConst.JSON_KEY_HOLIDAYMARGININITIAL)));
                }
                if(isMore){
                    if(i == mMarginList.getDataCount() - 1){
                        lots += "\n" + AppMain.getAppString(R.string.property_lots)+">"+item.getString(GTSConst.JSON_KEY_VOLUMESMIN);
                    }else{
                        lots += "\n" + item.getString(GTSConst.JSON_KEY_VOLUMESMIN) + "<"+AppMain.getAppString(R.string.property_lots)+"≤"+item.getString(GTSConst.JSON_KEY_VOLUMESMAX);
                    }
                    margin += "\n" + calCNY(isCNY,item.getString(GTSConst.JSON_KEY_MARGININITIAL));
                    holidayMargin += "\n" + calCNY(isCNY,item.getString(GTSConst.JSON_KEY_HOLIDAYMARGININITIAL));
                }
                mMarginModel.setStringValue(GTSConst.JSON_KEY_MARGINHEDGED, item.getString(GTSConst.JSON_KEY_MARGINHEDGED));
            }
            if(isMore){
                mMarginModel.setStringValue(GTSConst.JSON_KEY_PROPERTY_LOTS, lots);
                mMarginModel.setStringValue(GTSConst.JSON_KEY_PROPERTY_MARGIN, margin);
                mMarginModel.setStringValue(GTSConst.JSON_KEY_PROPERTY_HOLIDAYMARGIN, holidayMargin);
            }
        }else{
            if (!isEmpty){
                mMarginModel.setStringValue(GTSConst.JSON_KEY_MARGININITIAL, "0.00");
                mMarginModel.setStringValue(GTSConst.JSON_KEY_HOLIDAYMARGININITIAL, "0.00");
                mMarginModel.setStringValue(GTSConst.JSON_KEY_MARGINHEDGED, "0");
            }
        }
    }

    /**
     * 根据美元值返回具体的人民币值
     * @param value
     * @return
     */
    public String calCNY(boolean isCNY, String value){
        if(!isCNY){
            return DoubleConverter.toStringData(DoubleConverter.toDoubleData(value), 2);
        }
        double result = DoubleConverter.toDoubleData(value) * rate;
        Logger.e("calCNY = "+ DoubleConverter.toDoubleData(value) + ", "+ result);

        return DoubleConverter.toStringData(result, 2);
    }

    /**
     * 判断字段是否为空
     *
     * @param value
     * @return
     */
    private String getStr(String value) {
        if (value == null || value.length() < 1) {
            return "";
        }

        return value;
    }

    /**
     * 返回拼接字段值
     *
     * @param strID
     * @return
     */
    private String getStr(String value, int strID) {
        if (value == null || value.length() < 1) {
            return "";
        }

        return AppMain.getAppString(strID, value);
    }

    /**
     * 根据英文单词返回星期几
     * @param str
     * @return
     */
    private String getWeek(String str){
        if(str.contains(AppContances.WEEK_1)){
            return str.replace(AppContances.WEEK_1,AppMain.getAppString(R.string.property_monday));
        }else if(str.contains(AppContances.WEEK_2)){
            return str.replace(AppContances.WEEK_2,AppMain.getAppString(R.string.property_tue));
        }else if(str.contains(AppContances.WEEK_3)){
            return str.replace(AppContances.WEEK_3,AppMain.getAppString(R.string.property_wed));
        }else if(str.contains(AppContances.WEEK_4)){
            return str.replace(AppContances.WEEK_4,AppMain.getAppString(R.string.property_thursday));
        }else if(str.contains(AppContances.WEEK_5)){
            return str.replace(AppContances.WEEK_5,AppMain.getAppString(R.string.property_friday));
        }else if(str.contains(AppContances.WEEK_6)){
            return str.replace(AppContances.WEEK_6,AppMain.getAppString(R.string.property_saturdays));
        }else if(str.contains(AppContances.WEEK_7)){
            return str.replace(AppContances.WEEK_7,AppMain.getAppString(R.string.property_sunday));
        }else{
            return str.replace(AppContances.WEEK_7,AppMain.getAppString(R.string.property_sunday));
        }
    }

    /**
     * 根据英文单词返回星期几
     * @param str
     * @return
     */
    private String getWeek(JSONObject str){
        String week = "";
        if(str.toString().contains(AppContances.WEEK_1)){
            week = AppMain.getAppString(R.string.property_monday) +":" + str.optString(AppContances.WEEK_1);
        }else if(str.toString().contains(AppContances.WEEK_2)){
            week = AppMain.getAppString(R.string.property_tue)+":" + str.optString(AppContances.WEEK_2);
        }else if(str.toString().contains(AppContances.WEEK_3)){
            week = AppMain.getAppString(R.string.property_wed)+":" + str.optString(AppContances.WEEK_3);
        }else if(str.toString().contains(AppContances.WEEK_4)){
            week = AppMain.getAppString(R.string.property_thursday)+":" + str.optString(AppContances.WEEK_4);
        }else if(str.toString().contains(AppContances.WEEK_5)){
            week = AppMain.getAppString(R.string.property_friday)+":" + str.optString(AppContances.WEEK_5);
        }else if(str.toString().contains(AppContances.WEEK_6)){
            week = AppMain.getAppString(R.string.property_saturdays)+":" + str.optString(AppContances.WEEK_6);
        }else if(str.toString().contains(AppContances.WEEK_7)){
            week = AppMain.getAppString(R.string.property_sunday)+":" + str.optString(AppContances.WEEK_7);
        }else{
            week = AppMain.getAppString(R.string.property_sunday)+":" + str.optString(AppContances.WEEK_7);
        }

        return week;
    }

    /**
     * 获取交易时间
     * @param tradeTime
     * @return
     */
    private String getTradeTime(JSONArray tradeTime){
        if(null == tradeTime || tradeTime.length() < 1){
            return "";
        }

        String strTime = "";
        for (int i = 0 ; i < tradeTime.length(); i++){
            String str = getWeek(tradeTime.optJSONObject(i));
            if(str.length() > 0){
                if(i == 0){
                    strTime = str;
                }else{
                    strTime = strTime + "\n" + str;
                }
            }
        }

        return strTime;
    }

}
